package br.com.jk.util.pesquisa;

import br.com.jk.util.Util;
import br.com.jk.util.pesquisa.Pesquisa.Opcao;
import br.com.jk.util.pesquisa.Pesquisa.Tipo;
import java.awt.event.KeyEvent;

/**
 *
 * @author camilo
 */
public class PesquisaJDialog extends javax.swing.JDialog {

  private static PesquisaJDialog pesqDialog;
  public static Pesquisa pesquisa;

  /**
   * Creates new form Pesquisa
   */
  private PesquisaJDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();

  }

  public static PesquisaJDialog getInstance(java.awt.Frame parent, boolean modal) {
    if (pesqDialog == null) {
      pesqDialog = new PesquisaJDialog(parent, modal);
    }
    return pesqDialog;
  }

  public static Pesquisa getCriterio(Tipo tipo) {
    PesquisaJDialog.getInstance(null, true);
    pesqDialog.setEnabledComponents(tipo);
    pesqDialog.setVisible(true);
    return pesquisa;
  }

  /**
   * This method is called from within the constructor to initialize the form. WARNING: Do NOT
   * modify this code. The content of this method is always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    bgOpcoesPesquisa = new javax.swing.ButtonGroup();
    jpDados = new javax.swing.JPanel();
    jpData = new javax.swing.JPanel();
    jlDataIn = new javax.swing.JLabel();
    jftfDataIn = new javax.swing.JFormattedTextField();
    jlDataFin = new javax.swing.JLabel();
    jftfDataFin = new javax.swing.JFormattedTextField();
    jpCriterio = new javax.swing.JPanel();
    jtfCriterio = new javax.swing.JTextField();
    jpOpcoes = new javax.swing.JPanel();
    jrbContendo = new javax.swing.JRadioButton();
    jrbIgual = new javax.swing.JRadioButton();
    jrbInicia = new javax.swing.JRadioButton();
    jrbTermina = new javax.swing.JRadioButton();
    jrbMaior = new javax.swing.JRadioButton();
    jrbMenor = new javax.swing.JRadioButton();
    jrbDiferente = new javax.swing.JRadioButton();
    jbSelecionar = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Pesquisa");
    setModal(true);
    setResizable(false);

    jpData.setLayout(new java.awt.GridLayout(1, 0));

    jlDataIn.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    jlDataIn.setText("Data In.");
    jpData.add(jlDataIn);

    try {
      jftfDataIn.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
    } catch (java.text.ParseException ex) {
      ex.printStackTrace();
    }
    jftfDataIn.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    jpData.add(jftfDataIn);

    jlDataFin.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    jlDataFin.setText("Data Fin.");
    jpData.add(jlDataFin);

    try {
      jftfDataFin.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
    } catch (java.text.ParseException ex) {
      ex.printStackTrace();
    }
    jftfDataFin.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    jpData.add(jftfDataFin);

    jtfCriterio.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfCriterioKeyPressed(evt);
      }
    });

    javax.swing.GroupLayout jpCriterioLayout = new javax.swing.GroupLayout(jpCriterio);
    jpCriterio.setLayout(jpCriterioLayout);
    jpCriterioLayout.setHorizontalGroup(
      jpCriterioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jtfCriterio, javax.swing.GroupLayout.DEFAULT_SIZE, 367, Short.MAX_VALUE)
    );
    jpCriterioLayout.setVerticalGroup(
      jpCriterioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jtfCriterio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    );

    javax.swing.GroupLayout jpDadosLayout = new javax.swing.GroupLayout(jpDados);
    jpDados.setLayout(jpDadosLayout);
    jpDadosLayout.setHorizontalGroup(
      jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jpData, javax.swing.GroupLayout.PREFERRED_SIZE, 367, javax.swing.GroupLayout.PREFERRED_SIZE)
      .addComponent(jpCriterio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    );
    jpDadosLayout.setVerticalGroup(
      jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jpDadosLayout.createSequentialGroup()
        .addComponent(jpData, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jpCriterio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addGap(6, 6, 6))
    );

    jpOpcoes.setLayout(new javax.swing.BoxLayout(jpOpcoes, javax.swing.BoxLayout.PAGE_AXIS));

    bgOpcoesPesquisa.add(jrbContendo);
    jrbContendo.setMnemonic('c');
    jrbContendo.setSelected(true);
    jrbContendo.setText("Contendo");
    jpOpcoes.add(jrbContendo);

    bgOpcoesPesquisa.add(jrbIgual);
    jrbIgual.setMnemonic('i');
    jrbIgual.setText("Igual");
    jpOpcoes.add(jrbIgual);

    bgOpcoesPesquisa.add(jrbInicia);
    jrbInicia.setMnemonic('n');
    jrbInicia.setText("Inicia com");
    jpOpcoes.add(jrbInicia);

    bgOpcoesPesquisa.add(jrbTermina);
    jrbTermina.setMnemonic('t');
    jrbTermina.setText("Termina com");
    jpOpcoes.add(jrbTermina);

    bgOpcoesPesquisa.add(jrbMaior);
    jrbMaior.setMnemonic('m');
    jrbMaior.setText("Maior");
    jpOpcoes.add(jrbMaior);

    bgOpcoesPesquisa.add(jrbMenor);
    jrbMenor.setMnemonic('e');
    jrbMenor.setText("Menor");
    jpOpcoes.add(jrbMenor);

    bgOpcoesPesquisa.add(jrbDiferente);
    jrbDiferente.setMnemonic('d');
    jrbDiferente.setText("Diferente");
    jpOpcoes.add(jrbDiferente);

    jbSelecionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/dialog-ok.png"))); // NOI18N
    jbSelecionar.setText("Pesquisar");
    jbSelecionar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbSelecionarActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jpDados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
        .addComponent(jpOpcoes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jbSelecionar, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(jpDados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jpOpcoes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
          .addComponent(jbSelecionar)))
    );

    pack();
    setLocationRelativeTo(null);
  }// </editor-fold>//GEN-END:initComponents

  private void jtfCriterioKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfCriterioKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
      jtfCriterio.setText(null);
    }
    if (evt.getKeyCode() == KeyEvent.VK_ENTER
            || evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
      criaPesquisa();
    }
  }//GEN-LAST:event_jtfCriterioKeyPressed

  private void jbSelecionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSelecionarActionPerformed
    criaPesquisa();
  }//GEN-LAST:event_jbSelecionarActionPerformed

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(PesquisaJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        PesquisaJDialog dialog = new PesquisaJDialog(new javax.swing.JFrame(), true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
          @Override
          public void windowClosing(java.awt.event.WindowEvent e) {
            System.exit(0);
          }
        });
        dialog.setVisible(true);
      }
    });
  }

  private void setEnabledComponents(Tipo tipo) {
    boolean dataFin;
    boolean dataIn;
    boolean criterio;
    boolean opContendo;
    boolean opIgual;
    boolean opInicia;
    boolean opTermina;
    boolean opMaior;
    boolean opMenor;
    boolean opDif;

    switch (tipo) {
      case BIGDECIMAL:
        dataFin = false;
        dataIn = false;
        criterio = true;
        opContendo = false;
        opIgual = true;
        opInicia = false;
        opTermina = false;
        opMaior = true;
        opMenor = true;
        opDif = true;
        break;
      case DATE:
        dataFin = true;
        dataIn = true;
        criterio = false;
        opContendo = false;
        opIgual = false;
        opInicia = false;
        opTermina = false;
        opMaior = false;
        opMenor = false;
        opDif = false;
        break;
      case DOUBLE:
        dataFin = false;
        dataIn = false;
        criterio = true;
        opContendo = false;
        opIgual = true;
        opInicia = false;
        opTermina = false;
        opMaior = true;
        opMenor = true;
        opDif = true;
        break;
      case INTEGER:
        dataFin = false;
        dataIn = false;
        criterio = true;
        opContendo = false;
        opIgual = true;
        opInicia = false;
        opTermina = false;
        opMaior = true;
        opMenor = true;
        opDif = true;
        break;
      case STRING:
        dataFin = false;
        dataIn = false;
        criterio = true;
        opContendo = true;
        opIgual = true;
        opInicia = true;
        opTermina = true;
        opMaior = false;
        opMenor = false;
        opDif = true;
        break;
      case CNPJ:
        dataFin = false;
        dataIn = false;
        criterio = true;
        opContendo = false;
        opIgual = true;
        opInicia = false;
        opTermina = false;
        opMaior = false;
        opMenor = false;
        opDif = true;
        break;
      case TELEFONE:
        dataFin = false;
        dataIn = false;
        criterio = true;
        opContendo = true;
        opIgual = true;
        opInicia = true;
        opTermina = true;
        opMaior = false;
        opMenor = false;
        opDif = true;
        break;
      default:
        throw new AssertionError();
    }

    jlDataIn.setEnabled(dataIn);
    jlDataFin.setEnabled(dataFin);
    jftfDataFin.setEnabled(dataFin);
    jftfDataIn.setEnabled(dataIn);
    jtfCriterio.setEnabled(criterio);
    jrbContendo.setEnabled(opContendo);
    jrbIgual.setEnabled(opIgual);
    jrbInicia.setEnabled(opInicia);
    jrbTermina.setEnabled(opTermina);
    jrbMaior.setEnabled(opMaior);
    jrbMenor.setEnabled(opMenor);
    jrbDiferente.setEnabled(opDif);

    jlDataFin.setVisible(dataFin);
    jlDataIn.setVisible(dataIn);
    jftfDataFin.setVisible(dataFin);
    jftfDataIn.setVisible(dataIn);
    jtfCriterio.setVisible(criterio);
    jrbContendo.setVisible(opContendo);
    jrbIgual.setVisible(opIgual);
    jrbInicia.setVisible(opInicia);
    jrbTermina.setVisible(opTermina);
    jrbMaior.setVisible(opMaior);
    jrbMenor.setVisible(opMenor);
    jrbDiferente.setVisible(opDif);
    
    this.repaint();
  }

  private void criaPesquisa() {
    Pesquisa p = new Pesquisa();
    if (jtfCriterio.getText().isEmpty()
            || jftfDataFin.getText().isEmpty()
            || jftfDataIn.getText().isEmpty()) {
      p.setCancel(true);
      pesquisa = p;
      sair();
    } else {
      if (jtfCriterio.isEnabled()) {
        p.setCriterio(jtfCriterio.getText());
      }

      p.setOpcao(getOpcao());
      if (jftfDataFin.isEnabled()) {
        p.setDataF(Util.formatDataSToD(jftfDataFin.getText()));
      }
      if (jftfDataIn.isEnabled()) {
        p.setDataI(Util.formatDataSToD(jftfDataIn.getText()));
      }
      pesquisa = p;
      sair();
    }
  }

  private Opcao getOpcao() {
    if (jrbContendo.isSelected()) {
      return Pesquisa.Opcao.CONTENDO;
    } else if (jrbDiferente.isSelected()) {
      return Pesquisa.Opcao.DIFERENTE;
    } else if (jrbIgual.isSelected()) {
      return Pesquisa.Opcao.IGUAL;
    } else if (jrbInicia.isSelected()) {
      return Pesquisa.Opcao.INICIA;
    } else if (jrbMaior.isSelected()) {
      return Pesquisa.Opcao.MAIOR;
    } else if (jrbMenor.isSelected()) {
      return Pesquisa.Opcao.MENOR;
    } else if (jrbTermina.isSelected()) {
      return Pesquisa.Opcao.TERMINA;
    } else {
      return Pesquisa.Opcao.CONTENDO;
    }
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.ButtonGroup bgOpcoesPesquisa;
  private javax.swing.JButton jbSelecionar;
  private javax.swing.JFormattedTextField jftfDataFin;
  private javax.swing.JFormattedTextField jftfDataIn;
  private javax.swing.JLabel jlDataFin;
  private javax.swing.JLabel jlDataIn;
  private javax.swing.JPanel jpCriterio;
  private javax.swing.JPanel jpDados;
  private javax.swing.JPanel jpData;
  private javax.swing.JPanel jpOpcoes;
  private javax.swing.JRadioButton jrbContendo;
  private javax.swing.JRadioButton jrbDiferente;
  private javax.swing.JRadioButton jrbIgual;
  private javax.swing.JRadioButton jrbInicia;
  private javax.swing.JRadioButton jrbMaior;
  private javax.swing.JRadioButton jrbMenor;
  private javax.swing.JRadioButton jrbTermina;
  private javax.swing.JTextField jtfCriterio;
  // End of variables declaration//GEN-END:variables

  private void sair() {
    pesqDialog = null;
    this.dispose();
  }
}
